package com.example.cd5160866.urlapp;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;


public class Demo7Activity extends AppCompatActivity {
    ViewPager viewPager;

    Button button;

    private int pagerWidth;

    private int currentPosition;

    private int[] colors = new int[]{Color.YELLOW, Color.RED, Color.BLACK, Color.BLUE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo_7);
        viewPager = (ViewPager) findViewById(R.id.vp);
        button = (Button) findViewById(R.id.bt);
        viewPager.setAdapter(new TestAdapter());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d("qw", "currentP " + currentPosition + " scrollP " + position + " px " + positionOffsetPixels);
                if (position == currentPosition) {
                    button.setTranslationX(-positionOffsetPixels);
                } else {
                    button.setTranslationX(pagerWidth - positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                viewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                pagerWidth = viewPager.getWidth();
            }
        });
    }


    private class TestAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return colors.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = new View(container.getContext());
            ViewPager.LayoutParams params = new ViewPager.LayoutParams();
            view.setBackgroundColor(colors[position]);
            container.addView(view, params);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

}
